import React, { Component } from "react";
import { mdRender } from "../common/Common";
import './TMarkdownEditor.css'
import {saveAs} from 'file-saver';
import TDom from '../common/TDom'
const navigationList = ['返回','文件','格式','功能']
const fileList = ['导入','导出']
const styleList = ['删除线','加粗','倾斜','代码','行内代码','链接','表格']
const funList = ['重置','查找','历史']
export default
class TMarkdownEditor extends Component{
  constructor(props){
    super(props);
    this.mdMount = React.createRef();
    this.state = {
      md : `输出：w,b;f(x)=$(w\\cdot x+b)$`,
      urlText : ''
    }
    this.count = 1
    this.historyList = []
  }

  componentDidMount(){
    mdRender(this.state.md, this.mdMount.current)
  }

  componentWillUnmount(){
    clearInterval(this.timeCount)
  }



  
  
  //text区域输入功能
  handleTextChange(event){
    this.setState({
      md :  event.target.value
    }, ()=>{mdRender(this.state.md, this.mdMount.current)})
   
  }
  
  //滑动条同步功能   不用
  handleOnscroll(event){
    if(event.target.id=="showMdArea")
      event.target.scrollTop = document.getElementById("mdTextarea").scrollTop
    else if(event.target.id=="mdTextarea")
      event.target.scrollTop = document.getElementById("showMdArea").scrollTop
  
  }

  //导航栏下拉框button
  handleNavigationListButton = (e)=>{
    switch(e.target.id){
      case '导入':
        document.getElementById('fileSlector').click()
        break;
      case '导出':
        var blob = new Blob([JSON.stringify(this.state.md)], {type: "text/plain;charset=utf-8"});
        saveAs(blob, `mdtext.md`);
        break;
      case '删除线':
        this.styleSetup('~~your text~~')
        break;
      case '加粗':
        this.styleSetup('**your text**')
        break;
      case '倾斜':
        this.styleSetup('*your text*')
        break;
      case '代码':
        this.styleSetup('```c\ncode\n```\n')
        break ;
      case '行内代码':
        this.styleSetup('` ccode`')
        break;
      case '链接'://此处只是弹出框，在handleUrlText实现render
        document.getElementById('urlDiv').style.display = 'flex'
        this.cancleButton('tableEidtor')()
        this.cancleButton('historyArea')()
        this.handleMaskIndex('up')
        break;
      case '表格':
        document.getElementById('tableEidtor').style.display = 'flex'
        this.cancleButton('historyArea')()
        this.cancleButton('urlDiv')()
        this.handleMaskIndex('up')
        break;
      case '重置':
        this.setState({
          md : ''
        },()=>{mdRender(this.state.md, this.mdMount.current)})
        break;
      case '查找':
        this.find()
        break;
      case '历史':
        document.getElementById('historyArea').style.display = 'flex'
        this.cancleButton('urlDiv')()
        this.cancleButton('tableEidtor')()
        break ;
    }
  }

  handleMaskIndex = (flag)=>{
    var mask =   document.getElementById('mask')
    if(flag =='up'){
      mask.style.visibility='visible'
      mask.style.zIndex = 0
    }else{
      mask.style.visibility='hidden'
      mask.style.zIndex = -1
    }
  }

  find =()=>{
    var tartxt = document.getElementById('mdTextarea').innerHTML
    console.log(tartxt.split('d')) 
    var tarList =tartxt.split('d') 
    if(tarList.length<1)
      return
    else{
      
      console.log('查询开始');
      document.getElementById('mdTextarea').innerHTML = ''
      for(let i=0;i<tarList.length;i++){
        let dom= document.createElement('span')
        dom.innerText = 'd'
        dom.style.color='red'
        document.getElementById('mdTextarea').append(tarList.length[i])
        document.getElementById('mdTextarea').append(dom)
      }

      this.setState({
        md:  document.getElementById('mdTextarea').innerHTML
      })
      this.forceUpdate()
    }
   

  }

  downloadFile () {

  }

  //导入文件实现功能
  handleFileChange =(event)=>{
    const files = event.target.files;
    let reader = new FileReader();
    for(let i = 0; i <= files.length-1;  i++){
      reader.onload = (e) => {  
        this.setState({
          md: e.target.result
        })
        mdRender(this.state.md, this.mdMount.current)
      }
      reader.readAsText(files[i])
    }
  }

  //导航栏点击下拉框功能
  handleNavigationButton = (e)=> {
    switch(e.target.id){
      case '返回':
        console.log(this.props.home);
        this.props.home()
        break;
      case '文件' :
        if(document.getElementById('fileList').style.display=='flex')
          document.getElementById('fileList').style.display = 'none'
        else
          document.getElementById('fileList').style.display = 'flex'
        break;
      case '格式' :
        if(document.getElementById('styleList').style.display=='flex')
          document.getElementById('styleList').style.display = 'none'
        else
          document.getElementById('styleList').style.display = 'flex'
          document.getElementById('styleList').style.left = '220px'
        break;
      case '功能':
        if(document.getElementById('funList').style.display=='flex')
          document.getElementById('funList').style.display = 'none'
        else
        document.getElementById('funList').style.display = 'flex'
          document.getElementById('funList').style.left = '220px'
        break;
      }
    
  }

  

  styleSetup(str){
    let mttxt = this.state.md.toString()
    let mttxtBefore = str
    mttxt=mttxtBefore.concat(mttxt)
    this.setState({
      md: mttxt
    },()=>{mdRender(this.state.md, this.mdMount.current)})
    //mdRender(this.state.md, this.mdMount.current)
  }

  handleHistoryAreaChange = (e) =>{
    document.getElementById('showHistory').innerHTML = this.historyList.map((item) =>{
      if(Object.keys(item)[0] === e.target.id)
        {
          console.log(item[e.target.id]);
          return item[e.target.id]
      }
    }).join('')
  
  }

  handleUrlText = (e) =>{
    this.setState({
      urlText : document.getElementById('urlText').value
    },()=>{
      if(this.state.urlText.length<=0)
      return 
      let url ="[`web name`]("
      url += this.state.urlText
      url += "')"
      this.styleSetup(url)
      document.getElementById('urlDiv').style.display = 'none'
    })
    this.handleMaskIndex('down')
  }

  // | Syntax      | Description |
  // | ----------- | ----------- |
  // | Header      | Title       |
  // | Paragraph   | Text        |
  //table 实际实现功能
  handleTable = (e) =>{
    let line = document.getElementById('line').value 
    let row = document.getElementById('row').value 
    let mdtext ='|'
    for(let i =0 ;i<row ;i++){
      if(i==0){
        for (let j = 0; j < line; j++) {
          mdtext +='标题|'
        }
        mdtext +='\n'
        mdtext +='|:'
        for (let j = 0; j < line; j++) {
          mdtext +='---:|'
        }
        mdtext +='\n'
      }
      mdtext +='|'
      for (let j = 0; j < line; j++) {
        mdtext +='内容|'
      }
      mdtext +='\n'
    }
    this.styleSetup(mdtext)
    document.getElementById('tableEidtor').style.display = 'none'
    this.handleMaskIndex('down')
  }

  saveTheHistory = () =>{
    this.timeCount = setInterval(()=>{
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth()
      let day = date.getDay()
      let hours = date.getHours()
      let minute = date.getMinutes()
      let second = date.getSeconds()
      date = year + '/' + month +'/' + day + ' ' + hours + ':' + minute + ':' +second
      let newList = [{[date]:this.state.md},...this.historyList]
      this.historyList = newList
      console.log(this.historyList);
      this.forceUpdate()
    },300000)
    this.count ++
    
  }

  

  //失去焦点事件
  handleOnblur = (e) =>{
    setTimeout(()=>{
      switch(e.target.id){
        case '文件':
          document.getElementById('fileList').style.display = 'none'
          break ;
        case '格式':
          document.getElementById('styleList').style.display = 'none'
          break ;
        case '功能':
          document.getElementById('funList').style.display = 'none'
          break ;
      }
    },200)
    
  }

  cancleButton = (id) =>{
    return () =>{
      var dom = document.getElementById(id)
      console.log(dom);
      if(typeof(dom)===undefined)
        return
      this.handleMaskIndex('down')
      document.getElementById(id).style.display = 'none'
    } 
  }

  recoverHistory = (e) =>{
    this.setState({
      md : document.getElementById('showHistory').innerHTML
    })
  }

  handleDrop = (e) =>{
    e.preventDefault()
    var  targetX = e.clientX - this.offsetX
    var  targetY = e.clientY + this.offsetY 
    document.getElementById(this.dargID).style.cssText = `display:flex;left:${targetX}px;top:${targetY}px;`
  }

  dargStart = (e) =>{
    this.dargID = e.target.id
    var divOffsetX = document.getElementById(this.dargID).offsetLeft;
    this.offsetX = e.clientX - divOffsetX
    var divOffsetY = document.getElementById(this.dargID).offsetTop;
    this.offsetY = e.clientY  - divOffsetY  
  }

  allowDrag = (e) =>{
    e.preventDefault()
  }

  snowDown = () =>{
    let d = document.createElement('div')
  }

  render(){
    console.log('render');
    
    if(this.count === 1){
      this.saveTheHistory()
    }
    return(
      <div id ='MDroot' onDragOver={this.allowDrag} onDrop={this.handleDrop} >
        <div id ='mask' className="mask" ></div>
        <div id='navigationList' className="navigationList" >
          {navigationList.map((item) => {
            return <input type='button' key={item} className="navigationListItem" id={item} value={item} onClick = {this.handleNavigationButton} onBlur={this.handleOnblur}/>
          })}
        </div>
        <div id='fileList' className="navigationListItemChoice">
          {fileList.map((item) =>{
            return <input type='button' key={item}  id={item} value={item} onClick = {this.handleNavigationListButton}/>
          })  }
        </div>
        <div id='funList' className="navigationListItemChoice">
          {funList.map((item) =>{
            return <input type='button' key={item}  id={item} value={item} onClick = {this.handleNavigationListButton}/>
          })  }
        </div>
        <div id='styleList' className="navigationListItemChoice">
          {styleList.map((item) =>{
            return <input type='button' key={item}  id={item} value={item} onClick = {this.handleNavigationListButton}/>
          })  }
        </div>
        
        <div>
          <input type= 'file' id='fileSlector' onChange={this.handleFileChange} hidden={true} />
        </div>
        <div style={{display:'flex', fontSize:'calc(18px + 1.5vw)',height:'90vh',marginTop:'10px' ,width:'90vw'}}>
            <textarea id = 'mdTextarea' className="mdTextarea"
              onChange= {this.handleTextChange.bind(this)}
              value = {this.state.md}
              >
            </textarea>
            <div id='showMdArea'  className="showMdArea" ref={this.mdMount} >
           
        </div>
        </div>
        
        {/* 表格弹出框 */}
        <div id = 'tableEidtor' draggable="true" className="tableEidtor" onDragStart={this.dargStart} >
          <span style={{fontSize:'larger',fontWeight:'900', marginBottom:'10px' ,borderBottom:'1px grey solid'}}>添加表格</span>
          <div className="row">
            行<input id='row' type="number" step="1" min="1" max="100" /> 
          </div>
          <div className="row">
            列<input id='line' type="number" step="1" min="1" max="100"/> 
          </div>
          <div className="row" style ={{marginTop:'10px',border:'1px grey solid',width:'fit-content'}}>
            <input type = 'button' value='取消' onClick={this.cancleButton('tableEidtor')}/>
            <input type = 'button' style = {{background :'#578aef'}}value='确认' onClick={this.handleTable}/>
          </div>
        </div>
        <div id = 'urlDiv' className="urlDiv"  draggable="true" onDragStart={this.dargStart} >
          <span style ={{fontSize:'larger',fontWeight:'900', marginBottom:'10px' ,borderBottom:'1px grey solid'}}> 输入URL</span>
          <input id = 'urlText' type= 'text' className="urlText" />
          <div className="row" style={{marginTop:'5px',width:'fit-context',marginLeft:'185px'}}>
            <input type = 'button' value = '取消' style={{width:'100px'}} onClick={this.cancleButton('urlDiv')} />
            <input type = 'button' value = '确认' style={{width:'100px',background :'#578aef'}} onClick={this.handleUrlText}/>
          </div>
        </div>
        <div id = 'historyArea'  draggable="true" className="historyArea" style={{background: 'white' }} onDragStart={this.dargStart}>
            <span className="historySpan">历史记录</span>
            <div className="row" style={{width:'100%' ,height:'100%', overflow: 'hidden' }}>
              <div className="strip" style={{height:'80%'}}>
                {this.historyList.map((item =>{
                  // return <option>{Object.keys(Object.keys(item)}</option>
                  // return <option>{Object.keys(item)}</option>
                  return <input type ='button' key = {Object.keys(item)} id = {Object.keys(item)} value = {Object.keys(item)} onClick = {this.handleHistoryAreaChange}/>
          
                }))}
              </div>
              <div className="strip" style={{width:'100%' ,height:'100%'}}>
                <div id ='showHistory' className = 'showHistory'></div>
                <div className="row" >
                  <input type='button' value = '取消' style={{width:'20%' ,marginLeft:'45%' , background:'white' }} onClick  ={this.cancleButton('historyArea')}/>
                  <input type='button' value = '恢复此版本' style={{width:'20%' ,marginLeft:'5%' ,background:'rgb(238, 253, 252)'}} onClick  ={this.recoverHistory}/>
                </div>
              </div>
            </div>
        </div>
      </div>                                                            

    )
  }
}